<?php

namespace App\Http\Controllers\V1;

use App\Helpers\Logger\SLogger;
use App\Helpers\RestResponseFactory;
use App\Helpers\RestUtils;
use App\Helpers\Utils;
use App\Http\Controllers\Controller;
use App\Models\Factory\CacheFactory;
use App\Models\Factory\CashFactory;
use App\Models\Factory\CoinFactory;
use App\Models\Factory\ComDeviceFactory;
use App\Models\Factory\DecryFactory;
use App\Models\Factory\DecryptFactory;
use App\Models\Factory\InviteFactory;
use App\Models\Factory\SignFactory;
use App\Models\Factory\SmsFactory;
use App\Models\Factory\UserCreditFactory;
use App\Models\Factory\UserFactory;
use App\Models\Orm\CoinLog;
use App\Models\Orm\Pay;
use App\Models\Orm\Sign;
use App\Models\Orm\UserAccountCash;
use App\Models\Orm\UserIncome;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 账号密码登录
 * Class LoginController
 * @package App\Http\Controllers\V1
 */
class LoginController extends Controller
{


    public function login(Request $request)
    {
        //接收参数
        $data = $request->input();

        //获取用户信息
        $check = UserFactory::getUserByMobile($data['phone']);
        if (!$check){
            return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(1124), 1124);
        }

        //检查密码是否正确
        if (!($check['password'] == $data['password'])){
            //密码不正确则放入缓存,并且设置时间

            CacheFactory::loginLimit($check['register_phone'],15*60);

            return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(1102), 1102);
        }


        //根据用户的主键生成token
        $token['token'] = md5("anwen".time().$check['id']);
        $result['invite_code'] = $token['invite_code'] = Utils::getInviteCode($check['id']);
        $result['wallet'] = $check['wallet'];
        $result['key'] = $check['key'];
        $result['link'] = "https://m.guomeiling.xin/?inviteCode=".$result['invite_code'];



        //把用户的唯一标识保存到数据库内
        UserFactory::addUserTokenByMobile($data['phone'],$token);
        $result['phone'] = $check['phone'];
        $result['token']     = $token['token'];
        //更新用户的最后登录时间
        UserFactory::addUserLassTime($data['phone']);

        return RestResponseFactory::ok($result);



    }

    //实名认证
    public function renzheng(Request $request)
    {
        //接收参数
        $data = $request->input();

        //拿到中间件里赋值的userId
        $user = $request -> get('user');

        $user->real_name = $data['real_name'];
        $user->idcard = $data['id_card'];

        if($user->save())
        {
            return RestResponseFactory::ok(RestUtils::getStdObj(),200);
        };


    }


    //签到
    public function sign(Request $request)
    {
        //接收参数
        $data = $request->input();
        //拿到中间件里赋值的userId
        $user = $request -> get('user');
        //获取用户签到信息
        $userSign = UserFactory::getSign($user->id);


//        //签到表中无数据,插入一条
        if(empty($userSign)){
            SignFactory::addSign($user->id);
            $number = Sign::EVERYDAY;
            $resultLog = CoinFactory::addCoinLog($user->id,$type=1,$number,$user->total);

            $resultUser = InviteFactory::addSignIncome($user->id,$number);
            $user -> total += $number;
            $user ->save();
            $info['number'] = $number;
            return RestResponseFactory::ok($info,200);
        }

        //开始事务
          DB::beginTransaction();

        $stime =  strtotime($userSign->stime);


        //进来了先判断今天是否签到过

        //今天开始和结束时间
        $begintime=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endtime=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        //昨天开始和结束时间
        $beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;


        if($stime>$begintime && $stime < $endtime)
        {
            //今天已经签到
            return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(20016), 20016);

        }

        //判断是否今天签到过
        //如果今天没有签到,就看昨天签到了没
        //如果昨天没有签到,那就连续天数清零
        //如果昨天钱到了,连续天数累计加一

        if($stime>$beginYesterday && $stime < $endYesterday)
        {
            $result = SignFactory::editSign($user->id);

            $number = Sign::ContinuityDAY;
            $resultLog = CoinFactory::addCoinLog($user->id,$type=1,$number,$user->total);

            $resultUser = InviteFactory::addSignIncome($user->id,$number);


            if($result && $resultLog && $resultUser)
            {
                $user -> total += $number;
                $user ->save();

                DB::commit();
            }else{
                SLogger::getStream()->info("签到获取积分失败");
                DB::rollBack();
            }

            $info['number'] = $number;
            return RestResponseFactory::ok($info,200);


        }else{
            try {

                $days = 1;
                $result = SignFactory::updateSign($user->id,$days);

                $number = Sign::EVERYDAY;//不连续每天签到

                $resultLog = CoinFactory::addCoinLog($user->id,$type=1,$number,$user->total);

                $resultUser = InviteFactory::addSignIncome($user->id,$number);


                if($result && $resultLog && $resultUser)
                {
                    $user -> total += $number;
                    $user ->save();

                    DB::commit();
                }else{
                    SLogger::getStream()->info("签到获取积分失败");
                    DB::rollBack();
                }
                $info['number'] = $number;
                return RestResponseFactory::ok($info,200);

            } catch (\Exception $e) {

                SLogger::getStream()->info("签到获取积分异常");
                SLogger::getStream()->info($e);
                DB::rollBack();

                return RestResponseFactory::ok(RestUtils::getStdObj(),200);
            }


        }






    }


}